<?php
/**
 * Created by jinqiang on 2025/5/15 10:07.
 * Copyright (c) 2025, Your Company. All rights reserved.
 */


namespace App\Http\Services\Produce;


use App\Http\Models\Mysql\Number3Table;
use App\Http\Models\Mysql\ProductSubcontractCountTable;
use App\Http\Models\Mysql\ProductSubcontractItemColourTable;
use App\Http\Models\Mysql\ProductSubcontractItemDetailBatchTable;
use App\Http\Models\Mysql\ProductSubcontractItemDetailCountTable;
use App\Http\Models\Mysql\ProductSubcontractItemDetailTable;
use App\Http\Models\Mysql\ProductSubcontractItemSizeTable;
use App\Http\Models\Mysql\ProductSubcontractItemTable;
use App\Http\Models\Mysql\ProductSubcontractSizePositionTable;
use App\Http\Models\Mysql\ProductSubcontractTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyPricingContractTable;
use App\Http\Models\Mysql\SsyPricingExamineTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListDetailsTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\SsyStyleImagesTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Models\Mysql\VerifyPriceTable;
use App\Http\Repository\LogRepository;
use Illuminate\Support\Facades\DB;

class ProcessingManageService
{
    public function search($param)
    {
        $conn = (new ProductSubcontractTable());
        //加工单号
        if($param['number'] ?? ""){
            if(preg_match("/^[a-zA-Z]/is", $param['number'])){
                $conn = $conn->where('number', 'like', $param['number']."%");
            }else{
                $conn = $conn->where('number', 'like', "%".$param['number']."%");
            }
        }
        //运营订单号 款号
        if($param['export_order_number'] ?? "" || $param['type_no'] ?? "" || $param['type_name'] ?? ""){
            $productSubcontractItemList = (new ProductSubcontractItemTable())->where(function($query) use($param){
                if($param['export_order_number'] ?? ""){
                    $query = $query->where('export_order_number', $param['export_order_number']);
                }
                if($param['type_no'] ?? ""){
                    if(preg_match("/^[a-zA-Z]/is", $param['type_no'])){
                        $query = $query->where('product_number', 'like', $param['type_no']."%");
                    }else{
                        $query = $query->where('product_number', 'like', "%".$param['type_no']."%");
                    }
                }
                if($param['type_name'] ?? ""){
                    $query->where('product', "like", "%".$param['type_name']."%");
                }
            })->get(['product_subcontract_id'])->toArray();
            if(empty($productSubcontractItemList)){
                return ['data' => [], 'total' => 0];
            }
            $productSubcontractIds = array_column($productSubcontractItemList, 'product_subcontract_id');
            $conn = $conn->whereIn('id', $productSubcontractIds);
        }
        if(isset($param['approval_state']) && $param['approval_state'] != ""){
            $conn = $conn->where('approval_state', (Int)$param['approval_state']);
        }
        //工厂名称
        if($param['supplier'] ?? ""){
            $conn = $conn->where('supplier', $param['supplier']);
        }
        //大货核价
        if($param['verify_price_number'] ?? ""){
            $conn = $conn->where('verify_price_number', $param['verify_price_number']);
        }
        //创建人
        if($param['creator'] ?? ""){
            $conn = $conn->where('creator', $param['creator']);
        }
        //合同交期
        if($param['delivery_date'] ?? []){
            $start = (strtotime($param['delivery_date'][0]) - strtotime("2017-12-06"))/(60*60*24);
            $end = (strtotime($param['delivery_date'][1]) - strtotime("2017-12-06"))/(60*60*24);
            $conn = $conn->whereBetween('delivery_date', [$start, $end]);
        }
        $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        $ids = array_column($res['data'], 'id');
        //运营订单明细
        $productSubcontractItemList = (new ProductSubcontractItemTable())->whereIn('product_subcontract_id', $ids)->get()->toArray();
        $typeNoList = array_column($productSubcontractItemList, 'product_number');
        $productSubcontractItemMap = array_column($productSubcontractItemList, null, 'product_subcontract_id');
        //款式图片
        $imgList = (new SsyStyleImagesTable())->whereIn('type_no', $typeNoList)->get(['type_no', 'thumb_images'])->toArray();
        $imgMap = array_column($imgList, 'thumb_images', 'type_no');
        //运营下单日期
        $productSubcontractItemDetailList = (new ProductSubcontractItemDetailTable())->whereIn('product_subcontract_id', $ids)
            ->get(['product_subcontract_id', 'customer_purchase_order_date'])->toArray();
        $productSubcontractItemDetailMap = array_column($productSubcontractItemDetailList, 'customer_purchase_order_date', 'product_subcontract_id');
        foreach ($res['data'] as &$item){
            $item['delivery_date'] = !empty($item['delivery_date']) ? date('Y-m-d', strtotime("2017-12-06"."+ {$item['delivery_date']} days")) : "";
            $item['creation_time'] = date('Y-m-d', $item['creation_time']+1512460800);
            $itemObj = $productSubcontractItemMap[$item['id']] ?? [];
            $itemObj['img'] = $imgMap[$itemObj['product_number']] ?? "";
            $item['item'] = $itemObj;
            $item['customer_purchase_order_date'] = date('Y-m-d', strtotime("2017-12-06"."+ {$productSubcontractItemDetailMap[$item['id']]} days"));
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function detail($id)
    {
        $productSubcontractObj = (new ProductSubcontractTable())->where('id', $id)->first()->toArray();
        $productSubcontractObj['delivery_date'] = !empty($productSubcontractObj['delivery_date']) ?
            date('Y-m-d', strtotime("2017-12-06"."+ {$productSubcontractObj['delivery_date']} days")) : "";
        $productSubcontractItem = (new ProductSubcontractItemTable())->where('product_subcontract_id', $id)->first()->toArray();
        $productSubcontractItem['f25'] = $productSubcontractItem['f25'] == 1 ? true : false;
        $productSubcontractItemColour = (new ProductSubcontractItemColourTable())->where('product_subcontract_id', $id)->first()->toArray();
        $productSubcontractItemDetail = (new ProductSubcontractItemDetailTable())->where('product_subcontract_id', $id)->first()->toArray();
        $productSubcontractItemDetail['customer_purchase_order_date'] = !empty($productSubcontractItemDetail['customer_purchase_order_date']) ?
            date('Y-m-d', strtotime("2017-12-06"."+ {$productSubcontractItemDetail['customer_purchase_order_date']} days")) : "";
        $productSubcontractItemDetailBatch = (new ProductSubcontractItemDetailBatchTable())->where('product_subcontract_id', $id)->first()->toArray();
        $productSubcontractSizePosition = (new ProductSubcontractSizePositionTable())->where('product_subcontract_id', $id)->orderBy('position', 'asc')->get()->toArray();
        $productSubcontractItemSize = (new ProductSubcontractItemSizeTable())->where('product_subcontract_id', $id)->get()->toArray();
        $productSubcontractItemSizeMap = array_column($productSubcontractItemSize, null, 'id');
        $productSubcontractCount = (new ProductSubcontractCountTable())->where('product_subcontract_id', $id)->get()->toArray();
        $productSubcontractCountMap = [];
        foreach ($productSubcontractCount as $item){
            if($productSubcontractItemSizeMap[$item['product_subcontract_item_size_id']] ?? []){
                $item['item_size'] = $productSubcontractItemSizeMap[$item['product_subcontract_item_size_id']];
                $productSubcontractCountMap[$item['item_size']['size']] = $item;
            }
        }
        $productSubcontractItemDetailCount = (new ProductSubcontractItemDetailCountTable())->where('product_subcontract_id', $id)->get()->toArray();
        $productSubcontractItemDetailCountMap = [];
        foreach ($productSubcontractItemDetailCount as $item){
            if($productSubcontractItemSizeMap[$item['product_subcontract_item_size_id']] ?? []){
                $item['item_size'] = $productSubcontractItemSizeMap[$item['product_subcontract_item_size_id']];
                $productSubcontractItemDetailCountMap[$item['item_size']['size']] = $item;
            }
        }
        return [
            'data' => $productSubcontractObj,
            'item' => $productSubcontractItem,
            'item_colour' => $productSubcontractItemColour,
            'item_detail' => $productSubcontractItemDetail,
            'item_detail_batch' => $productSubcontractItemDetailBatch,
            'size_position' => $productSubcontractSizePosition,
            'count' => $productSubcontractCountMap,
            'detail_count' => $productSubcontractItemDetailCountMap
        ];
    }

    public function del($id)
    {
        $productSubcontractObj = (new ProductSubcontractTable())->where('id', $id)->first()->toArray();
        if($productSubcontractObj['approval_state'] == 1){
            return ['code' => -1, 'msg' => '删除失败：当前单据已审核'];
        }
        $productSubcontractItemObj = (new ProductSubcontractItemTable())->where('product_subcontract_id', $id)->first()->toArray();
        (new ProductSubcontractTable())->deleteData($id);
        (new ProductSubcontractItemTable())->deleteDataWhere(['product_subcontract_id' => $id]);
        (new ProductSubcontractItemColourTable())->deleteDataWhere(['product_subcontract_id' => $id]);
        (new ProductSubcontractItemSizeTable())->deleteDataWhere(['product_subcontract_id' => $id]);
        (new ProductSubcontractSizePositionTable())->deleteDataWhere(['product_subcontract_id' => $id]);
        (new ProductSubcontractItemDetailTable())->deleteDataWhere(['product_subcontract_id' => $id]);
        (new ProductSubcontractItemDetailBatchTable())->deleteDataWhere(['product_subcontract_id' => $id]);
        (new ProductSubcontractCountTable())->deleteDataWhere(['product_subcontract_id' => $id]);
        (new ProductSubcontractItemDetailCountTable())->deleteDataWhere(['product_subcontract_id' => $id]);
        //写入操作日志
        $user = auth()->guard("api")->user();
        LogRepository::setOperateLog($user->name, "单据删除,款号:{$productSubcontractItemObj['product_number']}", $productSubcontractObj['number'], 2);
        return ['code' => 0];
    }

    public function check($id, $action)
    {
        $resp = (new ProductSubcontractTable())->updateData($id, ['approval_state' => $action == 'CHECK' ? 1 : 2]);
        if($action == 'UNCHECK'){
            return $resp;
        }
        //开始同步到成品加工单
        $detailObj = $this->detail($id);
        //dd($detailObj);
        //工厂信息
        if(!isset($detailObj['data']['supplier']) || empty($detailObj['data']['supplier'])){
            return ['code' => -1, 'msg' => '加工厂未设置'];
        }
        $factoryObj = (new SsyProcessingFactoryNameTable())->where('factory_name', $detailObj['data']['supplier'])->first();
        $factoryObj = !empty($factoryObj) ? $factoryObj->toArray() : [];
        if(empty($factoryObj)){
            return ['code' => -1, 'msg' => '加工厂不存在'];
        }
        $styleObj = (new StyleTable())->where('number', $detailObj['item']['product_number'])->first(['brand_id']);
        $subjects = array_column(config("scm.subject"), null, 'brand_id');
        $factoryObj['source_factory_groups_id'] = $subjects[$styleObj->brand_id]['supplier_id'] ?? "";
        $brandName = $subjects[$styleObj->brand_id]['brand_name'] ?? "";
        $brandCode = $subjects[$styleObj->brand_id]['brand_code_s'] ?? "";
        if(!isset($detailObj['data']['verify_price_number']) || empty($detailObj['data']['verify_price_number'])){
            return ['code' => -1, 'msg' => '大货核价编码缺少'];
        }
        //同步加工单核价审核
        //$this->addPricingExamine($detailObj, $factoryObj);
        //同步合同信息
        if(!isset($detailObj['data']['contract_number']) || empty($detailObj['data']['contract_number'])){
            return ['code' => -1, 'msg' => '未填写工厂合同号'];
        }
        $contractRes = $this->addPricingContract($factoryObj, $detailObj['data']);
        if($contractRes['code'] !== 0){
            return $contractRes;
        }
        $createTime = date('Y-m-d H:i:s');
        foreach ($detailObj['size_position'] as $item){
            $countObj = $detailObj['detail_count'][$item['size']];
            if(empty($countObj['count'])){
                continue;
            }
            $skuCode = $detailObj['item']['product_number'].$detailObj['item_colour']['colour_number'].$countObj['item_size']['size_number'];
            $processingObj = (new SsyProcessingListTable())->where('processing_code', $detailObj['data']['number'])->where('sku_code', $skuCode)->first();
            if(empty($processingObj)){
                $data = [
                    'type_name' => $detailObj['item']['product'],
                    'type_no' => $detailObj['item']['product_number'],
                    'color_code' => $detailObj['item_colour']['colour_number'],
                    'size_code' => $countObj['item_size']['size_number'],
                    'num' => $countObj['count'],
                    'sku_code' => $skuCode,
                    'processing_code' => $detailObj['data']['number'],
                    'factory_name' => $detailObj['data']['supplier'],
                    'supplier_id' => $factoryObj['supplier_id'],
                    'bunum' => $countObj['count'] + ceil($countObj['count'] *0.05),//默认溢装比为50%,
                    'createtime' => $createTime,
                    'factory_contract_no' => $detailObj['data']['contract_number'],
                    'countnum' => $detailObj['data']['count'],
                    'countprice' => $detailObj['data']['price'],
                    'advance_charge' => $detailObj['data']['advance'],//预付款
                    'embroidery_price' => $detailObj['data']['f8_price'],
                    'contract_date' => $detailObj['data']['delivery_date'],
                    'production_date' => "",//生成回复交期
                    'merchandiser' => $detailObj['data']['handler'],
                    'order_processor' => $detailObj['data']['f18'],
                    'adduser' => $detailObj['data']['creator'],
                    'embroidery_factory' => $detailObj['data']['f8_short'],
                    'printing_factory' => $detailObj['data']['f9_short'],
                    'bronzing_factory' => $detailObj['data']['f10_short'],
                    'gold_printing_factory' => $detailObj['data']['f11_short'],
                    'unit_price' => $detailObj['data']['verify_price_price'],
                    'add_date' => $detailObj['item_detail']['customer_purchase_order_date'],
                    'tb_time' => $createTime,
                    'verify_price_number' => $detailObj['data']['verify_price_number'], //大货核价编码
                    'export_order_number' => $detailObj['item']['export_order_number'], //运营订单编码
                    'source_type' => 1,
                    's_status' => 1,
                    "brand_name" => $brandName,
                    "brand_code" => $brandCode
                ];
                (new SsyProcessingListTable())->createData($data);
            }else{
                $data = [
                    'num' => $countObj['count'],
                    'factory_name' => $detailObj['data']['supplier'],
                    'supplier_id' => $factoryObj['supplier_id'],
                    'factory_contract_no' => $detailObj['data']['contract_number'],
                    'countnum' => $detailObj['data']['count'],
                    'countprice' => $detailObj['data']['price'],
                    'advance_charge' => $detailObj['data']['advance'],//预付款
                    'embroidery_price' => $detailObj['data']['f8_price'],
                    'contract_date' => $detailObj['data']['delivery_date'],
                    'merchandiser' => $detailObj['data']['handler'],
                    'order_processor' => $detailObj['data']['f18'],
                    'adduser' => $detailObj['data']['creator'],
                    'embroidery_factory' => $detailObj['data']['f8_short'],
                    'printing_factory' => $detailObj['data']['f9_short'],
                    'bronzing_factory' => $detailObj['data']['f10_short'],
                    'gold_printing_factory' => $detailObj['data']['f11_short'],
                    'unit_price' => $detailObj['data']['verify_price_price'],
                    'add_date' => $detailObj['item_detail']['customer_purchase_order_date'],
                    'source_type' => 1,
                    's_status' => 1,
                    'verify_price_number' => $detailObj['data']['verify_price_number'], //大货核价编码
                    'export_order_number' => $detailObj['item']['export_order_number'], //运营订单编码
                    'tb_time' => $createTime,
                ];
                (new SsyProcessingListTable())->updateData($processingObj->id, $data);
                //查看唯一码已生成且工厂名有更新替换 需更新唯一码的加工厂信息
                if($processingObj->is_create){
                    $whereParam = [
                        'processing_code' => $detailObj['data']['number'],
                        'sku_code' => $skuCode
                    ];
                    (new SsyProcessingListDetailsTable())->updateDataWhere($whereParam, [
                        'factory_name' => $detailObj['data']['supplier'],
                        'supplier_id' => $factoryObj['supplier_id'],
                    ]);
                }
            }
            //同步合同交期 取最近的加工单交期日期
            $processingRes = (new SsyProcessingListTable())->where('sku_code', $skuCode)->orderBy('createtime', 'desc')->first(['contract_date'])->toArray();
            $days = (strtotime($processingRes['contract_date']) - strtotime(date('Y-m-d'))) / (24*3600);
            (new SsyJyProductListTable())->updateDataWhere(['product_code' => $skuCode], [
                'arrivaldate' => $processingRes['contract_date'],
                'arrivaldate_title' => ((Int)$days)."天发货"
            ]);
        }
        return ['code' => 0, 'msg' => '操作成功'];
    }

    //同步合同信息
    public function addPricingContract($factoryObj, $param)
    {
        list($factoryContractNo, $contractDate, $orderProcessor) = [$param['contract_number'], $param['delivery_date'], $param['f18']];
        $contractObj = (new SsyPricingContractTable())->where('factory_contract_no', $factoryContractNo)->first();
        if(!empty($contractObj)){
            if($contractObj->factory_name != $factoryObj['factory_name']){
                return ['code' => -1, 'msg' => '合同号已存在，且签约工厂名不一致'];
            }
            if(in_array($contractObj->status, [1, 2]) || in_array($contractObj->b_status, [0, 1])){
                return ['code' => -1, 'msg' => '合同已在审批流程中, 请更换合同号再提交'];
            }
            return ['code' => 0, 'msg' => '合同已存在'];
        }else{
            $data = [
                "factory_name" => $factoryObj['factory_name'],
                "factory_contract_no" => $factoryContractNo,
                "contract_date" => $contractDate,
                "order_processor" => $orderProcessor,
                "createtime" => date("Y-m-d H:i:s"),
                "supplier_id" => $factoryObj['supplier_id'],
                "source_factory_groups_id" => $factoryObj["source_factory_groups_id"]
            ];
            return (new SsyPricingContractTable())->createData($data);
        }
    }

    //同步加工单核价审核
    public function addPricingExamine($detailObj, $factoryObj)
    {
        $verifyPriceObj = (new VerifyPriceTable())->where('number', $detailObj['data']['verify_price_number'])->first()->toArray();
        $exist = (new SsyPricingExamineTable())->where('processing_code', $detailObj['data']['number'])->first();
        if(empty($exist)){
            $save = [
                "factory_contract_no" => $detailObj['data']['contract_number'],
                "type_no" => $detailObj['item']['product_number'],
                "supplier_id" => $factoryObj['supplier_id'],
                "factory_name" => $factoryObj['factory_name'],
                "processing_code" => $detailObj['data']['number'],
                "big_pricing_number" => $detailObj['data']['verify_price_number'], //核价编码
                "big_pricing_price" => $verifyPriceObj['f67'] ?? 0, //成本加价总价
                "process_pricing_price" => $verifyPriceObj['f65'] ?? 0,//成衣成本加价总价
                "order_processor" => $detailObj['data']['f18'],
                "createtime" => date("Y-m-d H:i:s")
            ];
            return (new SsyPricingExamineTable())->createData($save);
        }else{
            $save = [
                "factory_contract_no" => $detailObj['data']['contract_number'],//合同
                "big_pricing_number" => $detailObj['data']['verify_price_number'],//大货核价编码
                "big_pricing_price" => $verifyPriceObj['f67'] ?? 0, //成本加价总价
                "process_pricing_price" => $verifyPriceObj['f65'] ?? 0,//成衣成本加价总价
            ];
            return (new SsyPricingExamineTable())->updateData($exist->id, $save);
        }
    }

    public function save($param)
    {
        $user = auth()->guard("api")->user();
        list($editForm, $editCount, $editDetailCount, $editItem, $editItemColour, $editItemDetail, $editItemDetailBatch, $sizeList) = [
            json_decode($param['edit_form'], true),
            json_decode($param['edit_count'], true),
            json_decode($param['edit_detail_count'], true),
            json_decode($param['edit_item'], true),
            json_decode($param['edit_item_colour'], true),
            json_decode($param['edit_item_detail'], true),
            json_decode($param['edit_item_detail_batch'], true),
            json_decode($param['size_list'], true)
        ];
        //dd($editForm, $editCount, $editDetailCount, $editItem, $editItemColour, $editItemDetail, $editItemDetailBatch, $sizeList);
        try{
            DB::connection("mysql_sj")->beginTransaction();
            //保存主表
            $productRes = $this->saveProduct($editForm, $user);
            if($productRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $productRes;
            }
            //保存Item、colour、item_detail表
            $productItemRes = $this->saveProductItem($productRes["product_subcontract_id"], $editItem[0], $editItemColour, $editItemDetail);
            if($productItemRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $productItemRes;
            }
            //保存item_detail_batch表
            $productItemDetailBatchRes = $this->saveProductItemDetailBatch($productRes['product_subcontract_id'],
                $productItemRes['product_subcontract_item_id'], $productItemRes['product_subcontract_item_detail_id'], $editItemDetailBatch, $editForm);
            if($productItemDetailBatchRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $productItemDetailBatchRes;
            }
            //保存尺码序列表
            $productSizePositionRes = $this->saveProductSizePosition($productRes['product_subcontract_id'], $sizeList);
            if($productSizePositionRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $productSizePositionRes;
            }
            //保存尺码、数量表、数量价格表
            $productSizeCountRes = $this->saveProductSizeCount($productRes['product_subcontract_id'],
                $productItemRes['product_subcontract_item_id'],
                $productItemRes['product_subcontract_item_detail_id'],
                $productItemRes['product_subcontract_item_colour_id'],
                $productItemDetailBatchRes['product_subcontract_item_detail_batch_id'],
                $productSizePositionRes['size_position'],
                $editCount,
                $editDetailCount
            );
            if($productSizeCountRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $productSizeCountRes;
            }
            DB::connection("mysql_sj")->commit();
            return $productSizeCountRes;
        }catch (\Exception $e){
            DB::connection("mysql_sj")->rollBack();
            return ['code' => -1, 'msg' => "提交失败：".$e->getMessage()];
        }
    }

    public function saveProduct($editForm, $user)
    {
        $f8Price = (Double)($editForm['f8_price'] ?? 0);
        if(empty($editForm['f8_short']) && !empty($f8Price)){
            return ['code' => -1, 'msg' => '缺少绣花厂'];
        }
        if(!empty($editForm['f8_short']) && empty($f8Price)){
            return ['code' => -1, 'msg' => '缺少绣花价'];
        }
        if($editForm['id'] ?? ""){
            $data = [
                'contract_number' => $editForm['contract_number'],
                "supplier" => $editForm['supplier'],
                "supplier_short" => $editForm['supplier_short'],
                "supplier_id" => $editForm['supplier_id'],
                "delivery_date" => (strtotime(date('Y-m-d', strtotime($editForm['delivery_date']))) - strtotime("2017-12-06"))/(60*60*24),
                "verify_price_price" => round((Double)($editForm['verify_price_price'] ?? 0), 2),
                "verify_price_id" => $editForm['verify_price_id'] ?? 0,
                "verify_price_number" => $editForm['verify_price_number'] ?? "",
                "verify_price_style_number" => $editForm['verify_price_style_number'] ?? "",
                "f8_price" => round((Double)$f8Price, 2),
                "f18" => $editForm['f18'],
                "f18_id" => 0,
                "handler" => $editForm['handler'] ?? "",
                "handler_id" => 0,
                "f8_id" => $editForm['f8_id'],
                "f8_short" => $editForm['f8_short'],
                "f9_id" => $editForm['f9_id'],
                "f9_short" => $editForm['f9_short'],
                "f10_id" => $editForm['f10_id'],
                "f10_short" => $editForm['f10_short'],
                "f11_id" => $editForm['f11_id'],
                "f11_short" => $editForm['f11_short'],
                "comment" => $editForm['comment'] ?? "",
                "count" => $editForm['count'],
                "price" => $editForm['price']
            ];
            $resp = (new ProductSubcontractTable())->updateData($editForm['id'], $data);
            $resp['product_subcontract_id'] = $editForm['id'];
            return $resp;
        }else{
            $number3 = (new Number3Table())->first();
            $number3Data = ['head' => date('ym'), 'count' => $number3->head == date('ym') ? $number3->count + 1 : 1];
            DB::connection("mysql_sj")->table("number_3")->update($number3Data);
            $data = [
                'number' => "PS".$number3Data['head'].str_pad($number3Data['count'],3,"0",STR_PAD_LEFT),
                'contract_number' => $editForm['contract_number'],
                "supplier" => $editForm['supplier'],
                "supplier_short" => $editForm['supplier_short'],
                "supplier_id" => $editForm['supplier_id'],
                "supplier_company_id" => 0,
                "delivery_date" => (strtotime(date('Y-m-d', strtotime($editForm['delivery_date']))) - strtotime("2017-12-06"))/(60*60*24),
                "verify_price_price" => round((Double)($editForm['verify_price_price'] ?? 0), 2),
                "verify_price_id" => $editForm['verify_price_id'] ?? 0,
                "verify_price_number" => $editForm['verify_price_number'] ?? "",
                "verify_price_style_number" => $editForm['verify_price_style_number'] ?? "",
                "f8_price" => round((Double)$f8Price, 2),
                "f18" => $editForm['f18'],
                "f18_id" => 0,
                "handler" => $editForm['handler'] ?? "",
                "handler_id" => 0,
                "f8_id" => $editForm['f8_id'],
                "f8_short" => $editForm['f8_short'],
                "f9_id" => $editForm['f9_id'],
                "f9_short" => $editForm['f9_short'],
                "f10_id" => $editForm['f10_id'],
                "f10_short" => $editForm['f10_short'],
                "f11_id" => $editForm['f11_id'],
                "f11_short" => $editForm['f11_short'],
                "count" => $editForm['count'],
                "price" => $editForm['price'],
                "currency_id" => 1,
                "advance" => 0,
                "comment" => $editForm['comment'] ?? "",
                "term" => "",
                "address" => "",
                "payment_verify_price_id" => 0,
                "payment_verify_price_number" => "",
                "payment_verify_price_price" => 0,
                "state" => 0,
                "approval_state" => 0,
                "payment_state" => 0,
                'creator_id' => 5,//$user->id, //数加系统 用户查看权限问题，默认用户 5
                "creator" => $user->name,
                'creation_time' => strtotime(date('Y-m-d')) - 1512460800,
                'f27' => 0
            ];
            $resp = (new ProductSubcontractTable())->createData($data);
            $resp['product_subcontract_id'] = $resp['id'] ?? "";
            return $resp;
        }
    }

    public function saveProductItem($productSubcontractId, $editItem, $editItemColour, $editItemDetail)
    {
        $res = ['code' => 0];
        //Item表
        if($editItem['id'] ?? ""){
            $resp = (new ProductSubcontractItemTable())->updateData($editItem['id'], ['f25' => $editItem['f25'] ? 1 : 0]);
            if($resp['code'] !== 0){
                return $resp;
            }
            $res['product_subcontract_item_id'] = $editItem['id'];
        }else{
            $data = [
                "product_subcontract_id" => $productSubcontractId,
                "order_id" => $editItem['order_id'],
                "order_number" => $editItem['order_number'],
                "order_type" => $editItem['order_type'],
                "customer_id" => 0,
                "customer" => "",
                "customer_short" => "",
                "customer_company_id" => 0,
                "product_id" => $editItem['product_id'],
                "product_number" => $editItem['product_number'],
                "product" => $editItem['product'],
                "product_category_id" => $editItem['product_category_id'],
                "product_category" => $editItem['product_category'],
                "product_detail_category_id" => $editItem['product_detail_category_id'],
                "product_detail_category" => $editItem['product_detail_category'],
                "t17_id" => $editItem['t17_id'],
                "f25" => $editItem['f25'] ? 1 : 0,
                "f26" => $editItem['f26'],
                "export_order_number" => $editItem['export_order_number']
            ];
            $resp = (new ProductSubcontractItemTable())->createData($data);
            if($resp['code'] !== 0){
                return $resp;
            }
            $res['product_subcontract_item_id'] = $resp['id'];
        }
        //colour颜色表
        if($editItemColour['id'] ?? ""){
            $res['product_subcontract_item_colour_id'] = $editItemColour['id'];
        }else{
            $data = [
                'product_subcontract_id' => $productSubcontractId,
                'product_subcontract_item_id' => $res['product_subcontract_item_id'],
                'colour_id' => $editItemColour['colour_id'],
                'colour_number' => $editItemColour['colour_number'],
                'colour' => $editItemColour['colour'],
                'colour_value' => $editItemColour['colour_value']
            ];
            $resp = (new ProductSubcontractItemColourTable())->createData($data);
            if($resp['code'] !== 0){
                return $resp;
            }
            $res['product_subcontract_item_colour_id'] = $resp['id'];
        }
        //item_detail表
        if($editItemDetail['id'] ?? ""){
            $res['product_subcontract_item_detail_id'] = $editItemDetail['id'];
        }else{
            $data = [
                'product_subcontract_id' => $productSubcontractId,
                'product_subcontract_item_id' => $res['product_subcontract_item_id'],
                'customer_purchase_order_number' => $editItemDetail['customer_purchase_order_number'],
                'customer_purchase_order_date' => (strtotime(date('Y-m-d', strtotime($editItemDetail['customer_purchase_order_date']))) - strtotime("2017-12-06"))/(60*60*24),
                'delivery_date' => $editItemDetail['delivery_date'],
                'country_id' => $editItemDetail['country_id'],
                'country' => $editItemDetail['country'],
                'port_id' => 0,
                'port' => "",
                'method_id' => 3,
                'comment' => $editItemDetail['comment'],
                'product_subcontract_item_colour_id' => $res['product_subcontract_item_colour_id'],
                'order_item_id' => 0
            ];
            $resp = (new ProductSubcontractItemDetailTable())->createData($data);
            if($resp['code'] !== 0){
                return $resp;
            }
            $res['product_subcontract_item_detail_id'] = $resp['id'];
        }
        return $res;
    }

    public function saveProductItemDetailBatch($productSubcontractId, $productSubcontractItemId, $productSubcontractItemDetailId, $editItemDetailBatch, $editForm)
    {
        $res = ['code' => 0];
        if($editItemDetailBatch['id'] ?? ""){
            $data = [
                'delivery_date' => (strtotime(date('Y-m-d', strtotime($editForm['delivery_date']))) - strtotime("2017-12-06"))/(60*60*24)
            ];
            $resp = (new ProductSubcontractItemDetailBatchTable())->updateData($editItemDetailBatch['id'], $data);
            if($resp['code'] !== 0){
                return $resp;
            }
            $res['product_subcontract_item_detail_batch_id'] = $editItemDetailBatch['id'];
        }else{
            $data = [
                'product_subcontract_id' => $productSubcontractId,
                'product_subcontract_item_id' => $productSubcontractItemId,
                'product_subcontract_item_detail_id' => $productSubcontractItemDetailId,
                'position' => 1,
                'delivery_date' => (strtotime(date('Y-m-d', strtotime($editForm['delivery_date']))) - strtotime("2017-12-06"))/(60*60*24)
            ];
            $resp = (new ProductSubcontractItemDetailBatchTable())->createData($data);
            if($resp['code'] !== 0){
                return $resp;
            }
            $res['product_subcontract_item_detail_batch_id'] = $resp['id'];
        }
        return $res;
    }

    public function saveProductSizePosition($productSubcontractId, $sizeList)
    {
        $res = ['code' => 0, 'size_position' => []];
        foreach ($sizeList as $item){
            if($item['id'] ?? ""){
                $data = [
                    'position' => $item['position'],
                    'size' => $item['size']
                ];
                $resp = (new ProductSubcontractSizePositionTable())->updateData($item['id'], $data);
                if($resp['code'] !== 0){
                    return $resp;
                }
                $res['size_position'][$item['size']] = $item['id'];
            }else{
                $data = [
                    'product_subcontract_id' => $productSubcontractId,
                    'position' => $item['position'],
                    'size' => $item['size']
                ];
                $resp = (new ProductSubcontractSizePositionTable())->createData($data);
                if($resp['code'] !== 0){
                    return $resp;
                }
                $res['size_position'][$item['size']] = $resp['id'];
            }
        }
        return $res;
    }

    public function saveProductSizeCount($productSubcontractId, $productSubcontractItemId, $productSubcontractItemDetailId, $productSubcontractItemColourId
        , $productSubcontractItemDetailBatchId, $sizePosition, $editCount, $editDetailCount)
    {
        foreach ($editDetailCount as $size => $item){
            $productItemSizeId = $item['item_size']['id'] ?? "";
            //保存item_size表
            if(empty($productItemSizeId)){
                $itemSizeData = [
                    'product_subcontract_id' => $productSubcontractId,
                    'product_subcontract_item_id' => $productSubcontractItemId,
                    'product_subcontract_size_position_id' => $sizePosition[$size],
                    'size_id' => $item['item_size']['size_id'],
                    'size_number' => $item['item_size']['size_number'],
                    'size' => $item['item_size']['size']
                ];
                $productItemSizeRes = (new ProductSubcontractItemSizeTable())->createData($itemSizeData);
                if($productItemSizeRes['code'] !== 0){
                    return $productItemSizeRes;
                }
                $productItemSizeId = $productItemSizeRes['id'];
            }
            //保存detail_count表
            $productItemDetailCountId = $item['id'] ?? "";
            if(empty($productItemDetailCountId)){
                $detailCountData = [
                    'product_subcontract_id' => $productSubcontractId,
                    'product_subcontract_item_id' => $productSubcontractItemId,
                    'product_subcontract_item_detail_id' => $productSubcontractItemDetailId,
                    'product_subcontract_item_colour_id' => $productSubcontractItemColourId,
                    'product_subcontract_size_position_id' => $sizePosition[$size],
                    'product_subcontract_item_size_id' => $productItemSizeId,
                    'source_product_subcontract_item_detail_count_id' => 0,
                    'order_count_id' => $item['order_count_id'],
                    'order_count_type' => $item['order_count_type'],
                    'count' => (Int)$item['count'],
                    'completed' => 0,
                    'price' => $item['price']
                ];
                $detailCountRes = (new ProductSubcontractItemDetailCountTable())->createData($detailCountData);
                if($detailCountRes['code'] !== 0){
                    return $detailCountRes;
                }
                $productItemDetailCountId = $detailCountRes['id'];
            }else{
                $detailCountData = [
                    'count' => (Int)$item['count'],
                    'price' => $item['price']
                ];
                $detailCountRes = (new ProductSubcontractItemDetailCountTable())->updateData($productItemDetailCountId, $detailCountData);
                if($detailCountRes['code'] !== 0){
                    return $detailCountRes;
                }
            }
            //保存count表
            $productItemCountId = $editCount[$size]['id'] ?? "";
            if(empty($productItemCountId)){
                $countData = [
                    'product_subcontract_id' => $productSubcontractId,
                    'product_subcontract_item_id' => $productSubcontractItemId,
                    'product_subcontract_item_detail_id' => $productSubcontractItemDetailId,
                    'product_subcontract_item_detail_batch_id' => $productSubcontractItemDetailBatchId,
                    'product_subcontract_item_colour_id' => $productSubcontractItemColourId,
                    'product_subcontract_size_position_id' => $sizePosition[$size],
                    'product_subcontract_item_size_id' => $productItemSizeId,
                    'source_product_subcontract_item_detail_count_id' => 0,
                    'product_subcontract_item_detail_count_id' => $productItemDetailCountId,
                    'order_count_id' => $item['order_count_id'],
                    'order_count_type' => $item['order_count_type'],
                    'count' => (Int)$item['count'],
                ];
                $countRes = (new ProductSubcontractCountTable())->createData($countData);
                if($countRes['code'] !== 0){
                    return $countRes;
                }
            }else{
                $countData = ['count' => (Int)$item['count']];
                $countRes = (new ProductSubcontractCountTable())->updateData($productItemCountId, $countData);
                if($countRes['code'] !== 0){
                    return $countRes;
                }
            }
        }
        return ['code' => 0, 'msg' => '数量表保存成功'];
    }
}
